import {Component, Input, OnInit, ViewChild} from "@angular/core";
import {ViewCell} from "ng2-smart-table";
import {
  NbDialogRef,
  NbDialogService,
  NbGlobalPhysicalPosition,
  NbPopoverDirective,
  NbToastrService
} from "@nebular/theme";
import {HttpClient} from "@angular/common/http";

@Component({
  template: `
      <button nbButton size="tiny" status="success" (click)="edit(dialogRef)">编辑</button>
      <button nbButton size="tiny" status="danger" [nbPopover]="templateRef" nbPopoverPlacement="top">删除</button>
      <ng-template #templateRef>
          <p style="margin: 5px;font-size: small">确定删除吗？<a href="javascript:void(0)" (click)="delete()">是</a></p>
      </ng-template>
      <ng-template #dialogRef>
          <nb-card>
              <nb-card-header>编辑-{{rowData['name']}}</nb-card-header>
              <nb-card-body>
                  <label>手环ID</label>
                  <input nbInput [(ngModel)]="rowData['ringId']">
                  <label>病区</label>
                  <input nbInput [(ngModel)]="rowData['zone']">
                  <label>联系人</label>
                  <input nbInput [(ngModel)]="rowData['contactPerson']">
                  <label>联系电话</label>
                  <input nbInput [(ngModel)]="rowData['contactPhone']">
              </nb-card-body>
              <nb-card-footer>
                  <button nbButton (click)="confirm()">确定</button>
              </nb-card-footer>
          </nb-card>
      </ng-template>
  `,
  styles: [
      `
          button {
              margin-left: 5px;
              margin-right: 5px;
          }

          input {
              margin-right: 5px;
          }
    `
  ]
})
export class BrwxdwxtTableRenderComponent implements ViewCell, OnInit {
  @ViewChild(NbPopoverDirective, {static: false}) popover: NbPopoverDirective;
  renderValue: string;

  @Input() value: string | number;
  @Input() rowData: any;
  dialogRef: NbDialogRef<any>;

  constructor(private httpClient: HttpClient, private toastrService: NbToastrService, private dialogService: NbDialogService) {

  }

  delete() {
    this.rowData['self'].delete(this.rowData['id']).then(res => {
      if (!res) {
        this.toastrService.show(
          '错误',
          `无法删除该记录`,
          {position: NbGlobalPhysicalPosition.TOP_RIGHT});
      }
      this.popover.hide();
    });
  }

  edit(dialogRef) {
    this.dialogRef = this.dialogService.open(dialogRef);
  }

  confirm() {
    this.rowData['self'].edit(this.rowData['id'],this.rowData).then(res=>{
      this.dialogRef.close();
      if(!res){
        this.toastrService.show(
          '错误',
          `无法修改该记录`,
          {position: NbGlobalPhysicalPosition.TOP_RIGHT});
      }
    });
  }

  ngOnInit() {
  }

}
